<template>
  <view class="pdf-scroll-container">
    <!-- 顶部标题栏 -->
    <view class="pdf-header">
      <view class="header-title">{{ contractInfo.name || '红薯山药平台供应链入驻合同' }}</view>
      <view class="page-indicator">
        第 {{ currentPage }} / {{ pdfPages.length }} 页
      </view>
    </view>
    
    <!-- PDF页面滚动区域 -->
    <scroll-view 
      class="pdf-scroll-view" 
      scroll-y 
      :scroll-top="scrollTop"
      @scroll="handleScroll"
    >
      <view class="pdf-page-container">
        <view 
          class="pdf-page-item" 
          v-for="(page, index) in pdfPages" 
          :key="index"
          :id="'page-' + (index + 1)"
          style="position: relative;"
        >
          <image 
            class="pdf-page-image" 
            :src="page.imgUrl" 
            mode="widthFix"
            @load="onImageLoad(index)"
          />
          <!-- 第4页签名、公章渲染 -->
          <template v-if="index === 3">
            <view v-if="partyASignature && isPartyA"
                  :style="{ position: 'absolute', left: page.partyASignPos.x + 'rpx', top: page.partyASignPos.y + 'rpx', width: '180rpx', height: '60rpx', transform: 'rotate(270deg)', 'transform-origin': 'left top' }">
              <image :src="partyASignature" mode="aspectFit" style="width: 100%; height: 100%;" />
            </view>
            <view v-if="partyBSignature && !isPartyA"
                  :style="{ position: 'absolute', left: page.partyBSignPos.x + 'rpx', top: page.partyBSignPos.y + 'rpx', width: '180rpx', height: '60rpx', transform: 'rotate(270deg)', 'transform-origin': 'left top' }">
              <image :src="partyBSignature" mode="aspectFit" style="width: 100%; height: 100%;" />
            </view>
            <view v-if="partyASeal && isPartyA"
                  :style="{ position: 'absolute', left: page.partyASealPos.x + 'rpx', top: page.partyASealPos.y + 'rpx', width: '80rpx', height: '80rpx' }">
              <image :src="partyASeal" class="seal-image" mode="aspectFit" style="width: 100%; height: 100%;" />
            </view>
            <view v-if="partyBSeal && !isPartyA"
                  :style="{ position: 'absolute', left: page.partyBSealPos.x + 'rpx', top: page.partyBSealPos.y + 'rpx', width: '80rpx', height: '80rpx' }">
              <image :src="partyBSeal" class="seal-image" mode="aspectFit" style="width: 100%; height: 100%;" />
            </view>
          </template>
          <view class="page-number">第 {{ index + 1 }} 页</view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 底部操作按钮 -->
    <view v-if="contractInfo.status === '未签署'" class="pdf-footer">
      <view class="left-buttons">
        <view 
          class="footer-btn" 
          @click="handleSignature"
          :style="{ opacity: canSign ? 1 : 0.5 }"
        >
          <image src="../../static/edit.png" mode="aspectFit" />
          <text class="btn-text">签名</text>
        </view>
        <view class="footer-btn" @click="handleSeal">
          <image src="../../static/seal.png" mode="aspectFit" class="seal-icon" />
          <text class="btn-text">公章</text>
        </view>
      </view>
      <button class="footer-btn submit-btn" @click="handleSubmit">
        <text class="submit-text">提交签署</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'

const pagePositions = ref([])
const currentPage = ref(1)
const scrollTop = ref(0)
const isPartyA = ref(true)
const partyASignature = ref('')
const partyBSignature = ref('')
const partyASeal = ref('')
const partyBSeal = ref('')
const hasSigned = ref(false) // 新增：是否已签名标志

// 计算属性：是否可以签名
const canSign = computed(() => {
  return !hasSigned.value && contractInfo.value.status === '未签署'
})

// 接收页面参数
const contractInfo = ref({
  id: '',
  name: '红薯山药平台供应链入驻合同',
  time: '',
  status: '未签署'
})

// PDF页面数据
const pdfPages = ref([
  { imgUrl: '/static/contract-page1.jpg', height: 0 },
  { imgUrl: '/static/contract-page2.jpg', height: 0 },
  { imgUrl: '/static/contract-page3.jpg', height: 0 },
  { 
    imgUrl: '/static/contract-page4.jpg', 
    height: 0,
    partyASignPos: { x: 180, y: 620 },
    partyASealPos: { x: 180, y: 460 },
    partyBSignPos: { x: 500, y: 620 },
    partyBSealPos: { x: 500, y: 460 }
  }
])

onMounted(() => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options || {}
  
  contractInfo.value = {
    ...contractInfo.value,
    id: options.id || '',
    name: decodeURIComponent(options.name || contractInfo.value.name),
    time: decodeURIComponent(options.time || ''),
    status: decodeURIComponent(options.status || '未签署'),
    role: options.role || '甲方'
  }
  
  isPartyA.value = contractInfo.value.role === '甲方'
  
  if (contractInfo.value.name) {
    uni.setNavigationBarTitle({ title: contractInfo.value.name })
  }
  
  setTimeout(calculatePagePositions, 1000)
  
  // 检查是否已有签名（从本地存储加载）
  if (isPartyA.value) {
    partyASignature.value = uni.getStorageSync('partyASignature') || ''
    hasSigned.value = !!partyASignature.value
  } else {
    partyBSignature.value = uni.getStorageSync('partyBSignature') || ''
    hasSigned.value = !!partyBSignature.value
  }
})

// 图片加载完成后计算位置
function onImageLoad(index) {
  nextTick(() => {
    const query = uni.createSelectorQuery()
    query.select(`#page-${index + 1}`).boundingClientRect()
    query.exec(res => {
      if (res[0]) {
        pdfPages.value[index].height = res[0].height
        calculatePagePositions()
      }
    })
  })
}

// 计算每页的位置信息
function calculatePagePositions() {
  let positions = []
  let currentPosition = 0
  
  pdfPages.value.forEach((page, index) => {
    positions.push({
      page: index + 1,
      start: currentPosition,
      end: currentPosition + (page.height || 800)
    })
    currentPosition += page.height || 800
  })
  
  pagePositions.value = positions
}

// 滚动事件处理
function handleScroll(e) {
  const scrollTop = e.detail.scrollTop
  const windowHeight = uni.getSystemInfoSync().windowHeight
  const viewportCenter = scrollTop + windowHeight / 2
  
  let visiblePage = 1
  
  for (let i = 0; i < pagePositions.value.length; i++) {
    const pos = pagePositions.value[i]
    if (viewportCenter >= pos.start && viewportCenter <= pos.end) {
      visiblePage = pos.page
      break
    }
  }
  
  if (visiblePage !== currentPage.value) {
    currentPage.value = visiblePage
  }
}

// 处理签名
function handleSignature() {
  if (!canSign.value) {
    uni.showToast({
      title: '您已经签过名了',
      icon: 'none'
    })
    return
  }
  
  uni.navigateTo({
    url: '/pages/signature/index',
    events: {
      signatureComplete: (imgData) => {
        if (isPartyA.value) {
          partyASignature.value = imgData
          uni.setStorageSync('partyASignature', imgData)
        } else {
          partyBSignature.value = imgData
          uni.setStorageSync('partyBSignature', imgData)
        }
        hasSigned.value = true
        uni.showToast({ 
          title: '签名添加成功', 
          icon: 'success',
          duration: 1500
        })
      }
    }
  })
}

// 处理公章
function handleSeal() {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0]
      
      if (isPartyA.value) {
        partyASeal.value = tempFilePath
      } else {
        partyBSeal.value = tempFilePath
      }
      
      uni.showToast({ 
        title: '公章上传成功', 
        icon: 'success'
      })
    },
    fail: (err) => {
      uni.showToast({ 
        title: '上传失败: ' + (err.errMsg || '未知错误'), 
        icon: 'none'
      })
    }
  })
}

// 处理提交签署
function handleSubmit() {
  // 校验签名和公章是否已完成
  const missingItems = []
  if (isPartyA.value) {
    if (!partyASignature.value) missingItems.push('甲方签名')
    if (!partyASeal.value) missingItems.push('甲方公章')
  } else {
    if (!partyBSignature.value) missingItems.push('乙方签名')
    if (!partyBSeal.value) missingItems.push('乙方公章')
  }
  
  if (missingItems.length > 0) {
    return uni.showToast({
      title: `请完成${missingItems.join('和')}`,
      icon: 'none'
    })
  }
  
  uni.showModal({
    title: '提交签署',
    content: '确定要提交签署吗？提交后将无法修改。',
    success: (res) => {
      if (res.confirm) {
        // 模拟提交到服务器
        uni.showLoading({ title: '提交中...' })
        
        setTimeout(() => {
          uni.hideLoading()
          
          // 清除本地存储的签名
          if (isPartyA.value) {
            uni.removeStorageSync('partyASignature')
          } else {
            uni.removeStorageSync('partyBSignature')
          }
          
          uni.showToast({ 
            title: '提交成功', 
            icon: 'success',
            success: () => {
              // 更新合同状态
              contractInfo.value.status = '已签署'
              // 返回上一页
              uni.navigateBack()
            }
          })
        }, 2000)
      }
    }
  })
}
</script>

<style scoped>
/* 原有样式保持不变 */
.pdf-scroll-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.pdf-header {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.page-indicator {
  font-size: 28rpx;
  color: #666;
}

.pdf-scroll-view {
  flex: 1;
  height: 1px;
}

.pdf-page-container {
  padding: 20rpx;
}

.pdf-page-item {
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  position: relative;
}

.pdf-page-image {
  width: 100%;
  display: block;
}

.page-number {
  padding: 15rpx;
  text-align: center;
  font-size: 26rpx;
  color: #999;
  border-top: 1rpx solid #eee;
}

.seal-image {
  border-radius: 50%;
  border: 1rpx solid #eee;
  background-color: rgba(255,255,255,0.8);
}

.pdf-footer {
  padding: 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
}

.left-buttons {
  display: flex;
  gap: 20rpx;
  width: 50%;
}

.footer-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: 500;
  border: none;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  gap: 8rpx;
}

.footer-btn::after {
  border: none;
}

.footer-btn image {
  width: 40rpx;
  height: 40rpx;
}

.seal-icon {
  filter: brightness(0);
}

.btn-text {
  font-size: 24rpx;
  color: black;
  line-height: 1;
}

.submit-btn {
  background-color: #ff4757;
  width: 50%;
}

.submit-text {
  font-size: 28rpx;
  font-weight: 500;
  color: #fff;
}
</style>